﻿/************************************************************************
* Copyright (c) 2018 All Rights Reserved.
* 命名空间：ZTService
* 文件名：UserTask
* 创建人：David Rodríguez
* 创建时间：2018/7/18 星期三 11:49:10
* 描述：
*************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ZTService
{
    public class UserTask
    {
        private static Dictionary<string, CancellationTokenSource> UserDic { get; set; } =
            new Dictionary<string, CancellationTokenSource>();


        public static void AddTask(string userId)
        {
            //新用户增加智投线程
            if (!UserDic.ContainsKey(userId))
            {
                var cts=new CancellationTokenSource();
                UserDic.Add(userId,cts );
                RunTask(cts);
            }
        }

        public static void CancleTask(string userId)
        {
            //根据用户查找相应的cts。并取消
            var cts = UserDic.FirstOrDefault(x => x.Key == userId).Value;
            cts?.Cancel();
            UserDic.Remove(userId);
        }


        public static void RunTask(CancellationTokenSource cts)
        {
            Task.Factory.StartNew(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    //处理逻辑
                    Thread.Sleep(5 * 1000);
                }
            });
        }
    }
}